# 图片定制工具 - PowerShell启动脚本
# 编码: UTF-8

# 设置控制台编码为UTF-8
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
$Host.UI.RawUI.WindowTitle = "图片定制工具 - 启动器"

# 颜色定义
$Colors = @{
    Success = "Green"
    Warning = "Yellow" 
    Error = "Red"
    Info = "Cyan"
    Header = "Magenta"
}

function Write-ColorText {
    param([string]$Text, [string]$Color = "White")
    Write-Host $Text -ForegroundColor $Colors[$Color]
}

function Show-Header {
    Clear-Host
    Write-Host ""
    Write-ColorText "===============================================" "Header"
    Write-ColorText "            🎨 图片定制工具启动器" "Header"
    Write-ColorText "===============================================" "Header"
    Write-Host ""
}

function Test-Command {
    param([string]$Command)
    try {
        & $Command --version *>$null
        return $true
    } catch {
        return $false
    }
}

function Install-Dependencies {
    Write-ColorText "📦 安装项目依赖..." "Info"
    
    # 尝试官方源
    $installCmd = "pip install -r requirements.txt --index-url https://pypi.org/simple/ --trusted-host pypi.org"
    
    try {
        Invoke-Expression $installCmd
        if ($LASTEXITCODE -eq 0) {
            Write-ColorText "✅ 依赖安装完成" "Success"
            return $true
        }
    } catch {
        Write-ColorText "⚠️  官方源安装失败，尝试国内镜像..." "Warning"
    }
    
    # 尝试豆瓣镜像
    $mirrorCmd = "pip install -r requirements.txt -i https://pypi.douban.com/simple/ --trusted-host pypi.douban.com"
    
    try {
        Invoke-Expression $mirrorCmd
        if ($LASTEXITCODE -eq 0) {
            Write-ColorText "✅ 依赖安装完成（使用镜像源）" "Success"
            return $true
        }
    } catch {
        Write-ColorText "❌ 依赖安装失败" "Error"
        return $false
    }
    
    return $false
}

# 主执行流程
Show-Header

# 设置项目目录
$ProjectDir = Split-Path -Parent $MyInvocation.MyCommand.Path
Set-Location $ProjectDir

Write-ColorText "📁 项目目录: $ProjectDir" "Info"
Write-Host ""

# 检查Python
if (-not (Test-Command "python")) {
    Write-ColorText "❌ 错误: 未检测到Python，请先安装Python 3.9+" "Error"
    Write-Host ""
    Write-ColorText "🔗 下载地址: https://www.python.org/downloads/" "Info"
    Read-Host "按任意键退出"
    exit 1
}

Write-ColorText "✅ Python版本检查:" "Success"
python --version
Write-Host ""

# 检查虚拟环境
if (-not (Test-Path "venv")) {
    Write-ColorText "🔧 创建虚拟环境..." "Info"
    python -m venv venv
    if ($LASTEXITCODE -ne 0) {
        Write-ColorText "❌ 虚拟环境创建失败" "Error"
        Read-Host "按任意键退出"
        exit 1
    }
    Write-ColorText "✅ 虚拟环境创建成功" "Success"
}

# 激活虚拟环境
Write-ColorText "🔄 激活虚拟环境..." "Info"
& "venv\Scripts\Activate.ps1"

if ($LASTEXITCODE -ne 0) {
    Write-ColorText "❌ 虚拟环境激活失败" "Error"
    Read-Host "按任意键退出"
    exit 1
}

Write-ColorText "✅ 虚拟环境已激活" "Success"
Write-Host ""

# 检查依赖
Write-ColorText "🔍 检查项目依赖..." "Info"
try {
    python -c "import flask" *>$null
    if ($LASTEXITCODE -ne 0) {
        throw "Flask未安装"
    }
    Write-ColorText "✅ 项目依赖已安装" "Success"
} catch {
    if (-not (Install-Dependencies)) {
        Read-Host "按任意键退出"
        exit 1
    }
}

# 验证关键组件
Write-ColorText "🔍 验证关键组件..." "Info"
python -c "import psd_tools; print('✅ PSD文件处理支持')" 2>$null
if ($LASTEXITCODE -ne 0) { Write-ColorText "⚠️  PSD文件处理支持未安装" "Warning" }

python -c "import cv2; print('✅ OpenCV图像处理支持')" 2>$null  
if ($LASTEXITCODE -ne 0) { Write-ColorText "⚠️  OpenCV图像处理支持未安装" "Warning" }

python -c "import PIL; print('✅ Pillow图像处理支持')" 2>$null
if ($LASTEXITCODE -ne 0) { Write-ColorText "⚠️  Pillow图像处理支持未安装" "Warning" }

Write-Host ""

# 检查数据库
if (-not (Test-Path "database.db")) {
    Write-ColorText "🗄️  初始化数据库..." "Info"
    python -c "from database import init_db; init_db()" 2>$null
    Write-ColorText "✅ 数据库初始化完成" "Success"
} else {
    Write-ColorText "✅ 数据库文件存在" "Success"
}

# 创建必要目录
@("uploads", "exports") | ForEach-Object {
    if (-not (Test-Path $_)) {
        New-Item -ItemType Directory -Path $_ -Force | Out-Null
    }
}
Write-ColorText "✅ 目录结构检查完成" "Success"

Write-Host ""
Write-ColorText "===============================================" "Header"
Write-ColorText "              🚀 启动服务器" "Header"  
Write-ColorText "===============================================" "Header"
Write-Host ""

Write-ColorText "🌐 本地访问地址: http://localhost:5000" "Info"
Write-ColorText "🌐 局域网访问: http://$env:COMPUTERNAME:5000" "Info"
Write-Host ""

Write-ColorText "💡 功能介绍:" "Info"
Write-ColorText "   📋 底板管理 - 上传和管理PSD/TIF底板文件" "Info"
Write-ColorText "   🤖 智能定位 - AI自动识别并定位图片" "Info"
Write-ColorText "   📁 导出管理 - 管理生成的定制图片" "Info"
Write-Host ""

Write-ColorText "⏹️  停止服务: 按 Ctrl+C" "Warning"
Write-ColorText "===============================================" "Header"
Write-Host ""

# 启动Flask应用
try {
    python run.py
} catch {
    Write-Host ""
    Write-ColorText "❌ 服务器启动失败，请检查错误信息" "Error"
    Write-Host ""
}

Write-Host ""
Write-ColorText "🔚 服务器已停止" "Info"
Read-Host "按任意键退出"
